import cv2
import cupy as cp
import numpy as np
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')

def find_available_cameras():
    available_cameras = []
    
    # 尝试检查多个设备索引 (0, 1, 2, ...)
    for i in range(5):  # 这里尝试最多检查 5 个设备
        cap = cv2.VideoCapture(i)
        if cap.isOpened():
            available_cameras.append(i)
            cap.release()
    print("Available cameras:", available_cameras)
    return available_cameras

def adaptive_gamma_correction(image, target_brightness=128):
    mean_brightness = np.mean(image)  # 计算当前亮度
    gamma = np.log(target_brightness) / np.log(mean_brightness)  # 自适应 Gamma
    gamma = max(0.5, min(gamma, 2.0))  # 限制 gamma 变化范围，防止过度调整
    gamma_table = np.array([((i / 255.0) ** gamma) * 255 for i in range(256)]).astype("uint8")
    return cv2.LUT(image, gamma_table)

def find_face(camera_image):
    if camera_image is None:
        logging.warning("警告: 输入图像为空，跳过人脸检测")
        return None,None

    # 加载 Haar 人脸分类器
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

    # 确保分类器成功加载
    if face_cascade.empty():
        logging.error("错误: 无法加载人脸分类器")
        return camera_image  # 返回原始图像，避免 `None`

    # 转换为灰度图像
    gray = cv2.cvtColor(camera_image, cv2.COLOR_BGR2GRAY)

    # 检测人脸
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)

    # 如果没有检测到人脸，直接返回原图
    if len(faces) == 0:
        logging.warning("未检测到人脸")
        return camera_image,None

    # 初始化最大面积和对应的框
    max_area = 0
    max_face = None

    # 遍历检测到的人脸，并找到最大人脸
    for (x, y, w, h) in faces:
        area = w * h  # 计算矩形面积
        if area > max_area:  # 如果当前人脸的面积比最大面积大
            max_area = area
            max_face = (x, y, w, h)

    # 如果找到最大人脸，则绘制框并提取人脸区域
    if max_face:
        x, y, w, h = max_face
        size = max(w, h)
        x = max(0, x - (size - w) // 2)
        y = max(0, y - (size - h) // 2)
        x = min(x, camera_image.shape[1] - size)
        y = min(y, camera_image.shape[0] - size)

        # 画最大人脸的框
        cv2.rectangle(camera_image, (x, y), (x + size, y + size), (255, 0, 0), 2)

        # 提取最大人脸区域
        largest_face_img = camera_image[y:y + size, x:x + size]

        # 保存最大人脸为文件（可选）
        cv2.imwrite("largest_face.jpg", largest_face_img)  # 将最大人脸保存为文件

        return camera_image, largest_face_img  # 返回带框的图像和最大人脸图像

    return camera_image ,None # 如果没有找到人脸，返回原图